#coding=utf-8

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
'''
n = 100 # 步数
# 一个随机行走者
steps = 2*np.random.randint(0,2,n)-1
x = range(n)
y = [ sum(steps[:i]) for i in range(n) ]
plt.plot(x,y)
plt.show(); exit(1)
'''
'''
# 100个随机行走者
n = 100
nwalker = 100
steps = [2*np.random.randint(0,2,n)-1 for x in range(nwalker)] # 前进/后退：步长+-1
x = [range(n) for i in range(nwalker)]
y = [ [ sum(steps[j][:i]) for i in range(n) ] for j in range(nwalker) ]
plt.close()
for i in range(nwalker):
    plt.plot(x[i], y[i])
plt.show()

'''

# 100个随机行走者
n = 100
nwalker = 100
steps = [2*np.random.randint(0,2,n)-1 for x in range(nwalker)] # 前进/后退：步长+-1
t = range(n)
x = [ [ sum(steps[j][:i]) for i in range(n) ] for j in range(nwalker) ]
xmean = np.mean(x, 0); xvar = np.var(x, 0)
plt.plot(t, xmean); plt.plot(t, xvar)
plt.show()

n = 1000
nwalker = 1000
t = range(1,n+1); x = np.zeros(nwalker) ;
xmean = np.zeros(n); xvar = np.zeros(n)
#print("x = ", x)
for j in range(n): # n 个时间步长

    for i in range(nwalker):
        x[i] += 2*np.random.randint(0,2,1)-1 # -1 / 1
    #print("x = ", x)
    xmean[j] = np.mean(x); xvar[j] = np.var(x)
    #print("xmean = ", xmean[j], "xvar = ", xvar[j])
plt.plot( t, xmean ); plt.plot( t, xvar)
plt.show()

'''
# animation: distribution of 1000 random walkers
def walk( nwalker, xfinal ):
    for i in range(nwalker):
        if( np.random.random() < 0.5 ): xfinal[i] += 1
        else: xfinal[i] -= 1
nwalker = 1000
nstep = 500
xfinal = np.zeros(nwalker)
fig, ax = plt.subplots()
#line, = plt.hist(xfinal, bins=np.arange(-100, 100, 6), rwidth=0.8, density=True)
def update(frame):
    walk(nwalker, xfinal)
    plt.cla(); plt.ylim(0, 0.16); plt.title("iter = %d"%frame)
    print("iter = ", frame)
    plt.hist(xfinal, bins=np.arange(-100, 100, 6), rwidth=0.8, density=True )
ani = animation.FuncAnimation(fig, update, range(nstep), interval=100)
plt.show()
ani.save("RandomWalkers.gif",fps=60)
'''